package com.da.javatest.leetCode;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author chenlida
 * @date 2019/2/16 11:34
 * @description
 */
public class Code962 {
    public static void main(String[] args) {
        System.out.println(
            new Code962().topKFrequent(new String[] {"i", "love", "leetcode", "i", "love", "coding"}, 3));
    }

    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>(words.length);
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        List<String> l = map.entrySet().stream().sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
            .sorted((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue())).map(e -> e.getKey())
            .collect(Collectors.toList());
        Collections.reverse(l);

        return l.subList(0, k);
    }
}
